package com.hpjz.emrecord.service.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.hpjz.common.SysConfig;
import com.hpjz.emrecord.bean.ResourcesBean;
import com.hpjz.emrecord.dao.ResourcesDao;
import com.hpjz.emrecord.service.IResourceService;
import com.hpjz.emrecord.web.vo.ResourcesVO;

@Service("resourceService")
public class ResourceServiceImpl implements IResourceService{

	@Resource
	private ResourcesDao resourcesDao;
	
	
	@Override
	public void insertResources(List<ResourcesVO> res) {
		
	}

	private  String upath = SysConfig.getSysConfigVal("upload.path");
	
	/**
	 * 上传资源
	 */
	@Override
	public void insertResource(CommonsMultipartFile[] files, 
			String imageType,String recordId) {
		  //上传文件
		 List<ResourcesBean> rbeans = this.uploadFile(files, imageType, recordId);
		 //将上传记录写入文件
		 this.resourcesDao.insertBatch(rbeans);
	}
	
	/**
	 * 上传资源
	 */
	@Override
	public void updateResource(CommonsMultipartFile[] files, 
			String imageType,String recordId){
		ResourcesBean rbean = new ResourcesBean();
		rbean.setRecordid(Long.valueOf(recordId));
		rbean.setImagetype(imageType);
		this.resourcesDao.delete(rbean);
		//上传文件
		List<ResourcesBean> rbeans = this.uploadFile(files, imageType, recordId);
		this.resourcesDao.insertBatch(rbeans);
	}
	
	
	 /**
	  * 上传文件
	  * @param files
	  * @param imageType
	  * @param recordId
	  * @return
	  */
	private List<ResourcesBean> uploadFile(CommonsMultipartFile[] files, 
			String imageType,String recordId){
		 List<ResourcesBean> beans = new ArrayList<>();
		  try {
			  for (CommonsMultipartFile file : files) {
					String orgName = file.getOriginalFilename();
					File newFile = new File(upath);
					if (!newFile.exists()) {
						newFile.mkdirs();
					}
					FileOutputStream os = new FileOutputStream(new File(upath+File.separator+orgName));
				   InputStream in = file.getInputStream();
                  //写入文件
				   IOUtils.write(IOUtils.toByteArray(in), os);
				   IOUtils.closeQuietly(os);
				   IOUtils.closeQuietly(in);
				   ResourcesBean bean = new ResourcesBean();
				   bean.setImagetype(imageType);
				   bean.setRecordid(Long.valueOf(recordId));
				  bean.setFilename(orgName);
                  bean.setCreatedate(new Date());
                  beans.add(bean);
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		  
		  return  beans;
		
	}
	

}
